package test.http;

import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.PreEncodedHttpField;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.BufferUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JettyPlainTextServer {
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
        ServerConnector connector = server.getBean(ServerConnector.class);
        HttpConfiguration config = connector.getBean(HttpConnectionFactory.class).getHttpConfiguration();
        config.setSendDateHeader(true);
        config.setSendServerVersion(true);

        PathHandler pathHandler = new PathHandler();
        server.setHandler(pathHandler);

        server.start();
        server.join();
    }

    public static class PathHandler extends AbstractHandler
    {
        PlainTextHandler _plainHandler=new PlainTextHandler();

        public PathHandler()
        {
            addBean(_plainHandler);
        }

        @Override
        public void setServer(Server server)
        {
            super.setServer(server);
            _plainHandler.setServer(server);
        }

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
        {
            if ("/plain-text".equals(target))
                _plainHandler.handle(target,baseRequest,request,response);
        }
    }

    public static class PlainTextHandler extends AbstractHandler
    {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
            baseRequest.setHandled(true);
            baseRequest.getResponse().getHttpFields().add(new PreEncodedHttpField(HttpHeader.CONTENT_TYPE, MimeTypes.Type.TEXT_PLAIN.asString()));
            baseRequest.getResponse().getHttpOutput().sendContent(BufferUtil.toBuffer("Plain Text").slice());
        }
    }
}
